package com.lanou.dllo.findfood.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.google.gson.Gson;

import com.lanou.dllo.findfood.activity.BaskCookingActivity;
import com.lanou.dllo.findfood.activity.HomeLastActivity;
import com.lanou.dllo.findfood.activity.HomePagelastActivity;
import com.lanou.dllo.findfood.activity.HotMenuActivity;
import com.lanou.dllo.findfood.activity.MagazineActivity;
import com.lanou.dllo.findfood.activity.HotUserActivity;
import com.lanou.dllo.findfood.adpter.HomeLastReclyerAdpter;
import com.lanou.dllo.findfood.R;
import com.lanou.dllo.findfood.adpter.HomeViewPagerAdpter;
import com.lanou.dllo.findfood.database.MySQLHomeRecyeBaseUtil;
import com.lanou.dllo.findfood.database.MySQLiteDataBaseUtil;
import com.lanou.dllo.findfood.dialog.CookProgressDialog;
import com.lanou.dllo.findfood.entity.HomeLastJson;
import com.lanou.dllo.findfood.entity.HomeLastResult;
import com.lanou.dllo.findfood.entity.HomeTopDeals;
import com.lanou.dllo.findfood.entity.HomeTopResult;
import com.lanou.dllo.findfood.entity.HomeTopdata;
import com.lanou.dllo.findfood.util.MyImageClick;
import com.lanou.dllo.findfood.util.MyItemClickListener;
import com.lanou.dllo.findfood.volley.VolleySington;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by dllo on 15/10/20.
 * 首页有一个广告的轮播viewPager  还有一个底部的左右图片显示
 */
public class HomeFragment extends Fragment implements MyItemClickListener, View.OnClickListener, MyImageClick {
    private ViewPager pager;
    private RecyclerViewHeader viewHeader;
    private RecyclerView recyclerView;
    private RequestQueue queue;
    private Handler handler;
    private HomeViewPagerAdpter perAdpter;//viewPager的适配器
    private HomeLastReclyerAdpter lastReclyerAdpter;
    private long tweet_id;
    private String place_name;
    private TextView foodPerson, hotmenu, shear, magazine;
    private int maxItem = 0;
    private int currentItem;
    private MySQLiteDataBaseUtil baseUtil;
    private MySQLHomeRecyeBaseUtil recyeBaseUtil;
    //
    /**
     * 广告轮播效果
     *
     * @param
     */
    private Runnable r = new Runnable() {
        @Override
        public void run() {
            currentItem++;
            maxItem = perAdpter.getCount();
            pager.setCurrentItem(currentItem % maxItem);
            handler.postDelayed(r, 3000);

        }
    };


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_home, null);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        inintView();

        List<HomeTopDeals> dealses = baseUtil.queryHomeViewPageData();
//        initData();

        if (dealses == null || dealses.size() == 0) {
            initData();

        } else {
            perAdpter.addData(dealses);
            handler.postDelayed(r, 3000);//图片轮播

        }

        // requestLast();

        //判断数据库当前是否有内容 为空的适合网络添加
        List<HomeLastResult> results = recyeBaseUtil.queryHomeRecylerData();
        if (results == null || results.size() == 0) {
            requestLast();
        } else {
            lastReclyerAdpter.addData(results);
        }

    }


    private void inintView() {

        baseUtil = new MySQLiteDataBaseUtil(getContext());
        queue = Volley.newRequestQueue(getContext());
        pager = (ViewPager) getActivity().findViewById(R.id.viewPager);
        perAdpter = new HomeViewPagerAdpter(getActivity().getSupportFragmentManager());
        pager.setAdapter(perAdpter);
        //数据库初始化
        recyeBaseUtil = new MySQLHomeRecyeBaseUtil(getContext());

        handler = new Handler();
        //初始化头布局
        viewHeader = (RecyclerViewHeader) getActivity().findViewById(R.id.header);
        //美食下面部分
        recyclerView = (RecyclerView) getActivity().findViewById(R.id.recyclerView);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        gridLayoutManager.setOrientation(LinearLayout.VERTICAL);
        recyclerView.setLayoutManager(gridLayoutManager);

        lastReclyerAdpter = new HomeLastReclyerAdpter(getActivity());
        recyclerView.setAdapter(lastReclyerAdpter);


        lastReclyerAdpter.setImageListener(this);//调用监听方法

        //将recyclerView添加到头布局
        viewHeader.attachTo(recyclerView, true);
        foodPerson = (TextView) getActivity().findViewById(R.id.foodPerson);
        foodPerson.setOnClickListener(this);

        hotmenu = (TextView) getActivity().findViewById(R.id.hotmenu);
        hotmenu.setOnClickListener(this);

        shear = (TextView) getActivity().findViewById(R.id.shear);
        shear.setOnClickListener(this);

        magazine = (TextView) getActivity().findViewById(R.id.magazine);
        magazine.setOnClickListener(this);


    }

    //美食信息下面
    private void requestLast() {
        String url = "http://api.meishixing.com/picture/picturelist/last/page=1&" +
                "city_id=7&session_id=00001227993a5661b25da19c79c2a7c9a6affc";
        StringRequest request = new StringRequest(url, new Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                HomeLastJson last = gson.fromJson(response, HomeLastJson.class);
                if (last != null) {
                    List<HomeLastResult> result = last.getResult();
                    if (result != null && result.size() > 0) {
                        lastReclyerAdpter.addData(result);
                        recyeBaseUtil.savaHomeRecylerView(result);

                    }
                }

            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        VolleySington.getInstance().addRequest(request);

    }


    //数据获得 广告栏的部分
    private void initData() {
        final CookProgressDialog anmition = new CookProgressDialog(getContext(), R.id.animaImg);
        anmition.show();
        String url = "http://apis.baidu.com/baidunuomi/openapi/searchdeals";
        String httpArg = "city_id=1300010000&cat_ids=326";
        //&location=121.594796%2C38.923399根据经纬度查看附件
        String path = url + "?" + httpArg;
        final StringRequest request = new StringRequest(path, new Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                HomeTopResult result = gson.fromJson(response, HomeTopResult.class);
                if (result != null) {
                    HomeTopdata homeTopdatas = result.getData();

                    if (homeTopdatas != null) {

                        List<HomeTopDeals> dealses = homeTopdatas.getDeals();
                        if (dealses != null && dealses.size() > 0) {
                            perAdpter.addData(dealses);
                            baseUtil.deleHomeViewpager();
                            baseUtil.savaHomeViewPager(dealses);
                            handler.postDelayed(r, 3000);

                        }


                    }
                    anmition.dismiss();

                }
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                error.printStackTrace();
                ;
            }
        }

        ) {
            @Override
            //在StringRespset结束之前写{}在大括号里面写 getHeaders() 自动重写方法
            //用Map方法键值对形势添加
            //添加请求头
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("apikey", "7df89e2ed7c7b92e1a2fe5ec8036d0cd");
                return map;
            }
        };

        VolleySington.getInstance().addRequest(request);


    }

    //美食下一页的详情页面
    @Override
    public void onItemClick(HomeLastResult result) {
        Intent intent = new Intent(getActivity(), HomeLastActivity.class);
        intent.putExtra("place_name", result.getPlace_name());
        intent.putExtra("tweet_id", result.getTweet_id());
        startActivity(intent);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.foodPerson://美食达人
                Intent intent = new Intent(getActivity(), HotUserActivity.class);
                startActivity(intent);
                break;
            case R.id.hotmenu://热门菜谱
                Intent intent1 = new Intent(getActivity(), HotMenuActivity.class);
                startActivity(intent1);

                break;
            case R.id.shear://晒厨艺
                Intent intent2 = new Intent(getActivity(), BaskCookingActivity.class);
                startActivity(intent2);
                break;
            case R.id.magazine://美食杂志
                Intent intent3 = new Intent(getActivity(), MagazineActivity.class);
                startActivity(intent3);

                break;

            default:
                break;
        }
    }

    /**
     * 美食轮播的详情回调接口
     *
     * @param result
     */
    @Override
    public void MyImageClick(HomeTopDeals result) {
        Intent intent = new Intent(getActivity(), HomePagelastActivity.class);
        intent.putExtra("deal_id", result.getDeal_id());
        startActivity(intent);

    }
}
